package com.grj.service.article;


import cn.hutool.json.JSONUtil;
import com.grj.model.article.entity.Comment;
import com.grj.service.article.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.data.redis.core.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 14505
 */
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.grj.service.article.mapper")
@EnableScheduling
@RequiredArgsConstructor
public class ArticleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ArticleApplication.class, args);
    }

    private final StringRedisTemplate stringRedisTemplate;

    private final RabbitTemplate rabbitTemplate;

    private final CommentService commentService;

    @Async
    @Scheduled(cron="*/3 * * * * ?")
    public void printVal2() {
        Set<String> keys = stringRedisTemplate.keys("article::like::*");
        if(keys != null){
            if(keys.size() != 0){
                CorrelationData correlationData = new CorrelationData();
                correlationData.setId(UUID.randomUUID().toString());
                //发送消息
                rabbitTemplate.convertAndSend("exchange","update","ok".getBytes(StandardCharsets.UTF_8),correlationData);
            }
        }
    }

    @Async
    @Scheduled(cron="*/1 * * * * ?")
    public void c() {
        List<String> comment = stringRedisTemplate.boundListOps("comment::ok").range(0, -1);
        if (comment != null){
            if(comment.size()!= 0){
                List<Comment> collect = comment.stream().map(c -> JSONUtil.toBean(c, Comment.class)).collect(Collectors.toList());
                commentService.saveOrUpdateBatch(collect);
                stringRedisTemplate.delete("comment::ok");
            }
        }
    }

    }
